import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, InputNumber, Space, Tag, Modal, message, Descriptions, Popconfirm, Switch, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { TextArea } = Input;

// 获取会员等级列表
const fetchLevels = async (params) => {
  return request('/api/v1/member/level', {
    method: 'GET',
    params,
  });
};

// 获取会员等级详情
const fetchLevelDetail = async (id) => {
  return request(`/api/v1/member/level/${id}`, {
    method: 'GET',
  });
};

// 创建会员等级
const createLevel = async (data) => {
  return request('/api/v1/member/level', {
    method: 'POST',
    data,
  });
};

// 更新会员等级
const updateLevel = async (data) => {
  return request(`/api/v1/member/level/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除会员等级
const deleteLevel = async (id) => {
  return request(`/api/v1/member/level/${id}`, {
    method: 'DELETE',
  });
};

const MemberLevel = () => {
  const [levels, setLevels] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [levelForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentLevel, setCurrentLevel] = useState(null);
  const [formTitle, setFormTitle] = useState('创建会员等级');

  // 获取会员等级列表
  const fetchLevelList = async () => {
    try {
      setLoading(true);
      const res = await fetchLevels({
        page: pagination.current,
        pageSize: pagination.pageSize,
      });
      if (res.success) {
        setLevels(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取会员等级列表失败');
      }
    } catch (error) {
      console.error('获取会员等级列表出错:', error);
      message.error('获取会员等级列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLevelList();
  }, [pagination.current, pagination.pageSize]);

  // 查看会员等级详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchLevelDetail(record.id);
      if (res.success) {
        setCurrentLevel(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取会员等级详情失败');
      }
    } catch (error) {
      console.error('获取会员等级详情出错:', error);
      message.error('获取会员等级详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加会员等级
  const handleAdd = () => {
    setFormTitle('创建会员等级');
    setCurrentLevel(null);
    levelForm.resetFields();
    levelForm.setFieldsValue({
      status: true,
      discount: 100,
      point_rate: 1,
    });
    setFormVisible(true);
  };

  // 处理编辑会员等级
  const handleEdit = (record) => {
    setFormTitle('编辑会员等级');
    setCurrentLevel(record);
    levelForm.resetFields();
    levelForm.setFieldsValue({
      name: record.name,
      code: record.code,
      points_limit: record.points_limit,
      discount: record.discount,
      point_rate: record.point_rate,
      description: record.description,
      status: record.status === 1,
      benefits: record.benefits,
    });
    setFormVisible(true);
  };

  // 处理删除会员等级
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await deleteLevel(id);
      if (res.success) {
        message.success('删除会员等级成功');
        fetchLevelList();
      } else {
        message.error(res.message || '删除会员等级失败');
      }
    } catch (error) {
      console.error('删除会员等级出错:', error);
      message.error('删除会员等级失败');
    } finally {
      setLoading(false);
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await levelForm.validateFields();
      setLoading(true);
      
      // 设置状态
      values.status = values.status ? 1 : 0;
      
      let res;
      if (currentLevel) {
        // 更新
        res = await updateLevel({
          id: currentLevel.id,
          ...values,
        });
      } else {
        // 创建
        res = await createLevel(values);
      }
      
      if (res.success) {
        message.success(`${currentLevel ? '更新' : '创建'}会员等级成功`);
        setFormVisible(false);
        fetchLevelList();
      } else {
        message.error(res.message || `${currentLevel ? '更新' : '创建'}会员等级失败`);
      }
    } catch (error) {
      console.error(`${currentLevel ? '更新' : '创建'}会员等级出错:`, error);
      message.error(`${currentLevel ? '更新' : '创建'}会员等级失败`);
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '等级名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '等级代码',
      dataIndex: 'code',
      key: 'code',
      width: 120,
    },
    {
      title: '所需积分',
      dataIndex: 'points_limit',
      key: 'points_limit',
      width: 120,
    },
    {
      title: '折扣率',
      dataIndex: 'discount',
      key: 'discount',
      width: 100,
      render: (text) => `${text / 10}折`,
    },
    {
      title: '积分倍率',
      dataIndex: 'point_rate',
      key: 'point_rate',
      width: 100,
      render: (text) => `${text}倍`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此会员等级吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              icon={<DeleteOutlined />} 
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            创建会员等级
          </Button>
        </div>
        
        <Table
          columns={columns}
          dataSource={levels}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 会员等级详情弹窗 */}
      <Modal
        title="会员等级详情"
        visible={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={700}
      >
        {currentLevel && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="等级名称" span={2}>{currentLevel.name}</Descriptions.Item>
            <Descriptions.Item label="等级代码">{currentLevel.code}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={currentLevel.status === 1 ? 'green' : 'red'}>
                {currentLevel.status === 1 ? '启用' : '禁用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="所需积分">{currentLevel.points_limit}</Descriptions.Item>
            <Descriptions.Item label="折扣率">{`${currentLevel.discount / 10}折`}</Descriptions.Item>
            <Descriptions.Item label="积分倍率">{`${currentLevel.point_rate}倍`}</Descriptions.Item>
            <Descriptions.Item label="会员权益" span={2}>{currentLevel.benefits || '-'}</Descriptions.Item>
            <Descriptions.Item label="等级描述" span={2}>{currentLevel.description || '-'}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{moment(currentLevel.created_at*1000).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{moment(currentLevel.updated_at*1000).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 会员等级表单弹窗 */}
      <Modal
        title={formTitle}
        visible={formVisible}
        onCancel={() => setFormVisible(false)}
        onOk={handleFormSubmit}
        confirmLoading={loading}
        width={700}
      >
        <Form
          form={levelForm}
          layout="vertical"
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="等级名称"
                rules={[{ required: true, message: '请输入等级名称' }]}
              >
                <Input placeholder="请输入等级名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="等级代码"
                rules={[{ required: true, message: '请输入等级代码' }]}
              >
                <Input placeholder="请输入等级代码，如：gold, platinum" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                name="points_limit"
                label="所需积分"
                rules={[{ required: true, message: '请输入所需积分' }]}
              >
                <InputNumber min={0} style={{ width: '100%' }} placeholder="升级所需积分" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="discount"
                label="折扣率"
                rules={[{ required: true, message: '请输入折扣率' }]}
              >
                <InputNumber min={10} style={{ width: '100%' }} placeholder="如：90表示9折" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="point_rate"
                label="积分倍率"
                rules={[{ required: true, message: '请输入积分倍率' }]}
              >
                <InputNumber min={1} step={0.1} style={{ width: '100%' }} placeholder="如：1.5表示1.5倍" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="benefits"
            label="会员权益"
          >
            <TextArea rows={3} placeholder="请输入会员权益，如：免费停车、生日礼品等" />
          </Form.Item>
          <Form.Item
            name="description"
            label="等级描述"
          >
            <TextArea rows={3} placeholder="请输入等级描述" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default MemberLevel;